﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web.Script.Serialization;

namespace Dqaqs.Host.RestSvc
{
	public class MethodRunService : IMethodRunService
	{
		public string ExecuteMethod(string category, string method, string mainDll, string parameters)
		{
			try
			{
				var fileName = Path.Combine(ConfigurationManager.AppSettings["codeBaseDir"],
				                            string.Format(@"{0}\{1}\{2}.dll", category, method, mainDll));
				var ps = (parameters ?? string.Empty).Split(",".ToCharArray());
				var rv = RemoteProxy.ExecuteAlgorithmImplenter(fileName, ps);
				var js = new JavaScriptSerializer();
				return js.Serialize( FormatResultForJson(rv) );
			}
			catch(Exception ex)
			{
				var js = new JavaScriptSerializer();
				if (ex.InnerException != null)
					return js.Serialize(new {Error = ex.InnerException.Message});
				return js.Serialize(new {Error = ex.Message});
			}
		}

		private static IEnumerable<IEnumerable<string[]>> FormatResultForJson(IEnumerable<string[,]> result)
		{
			return
				result.Select( ArrayToJagged );
		}

		private static IEnumerable<string[]> ArrayToJagged(string[,] ar)
		{
			for (var i = 0; i <= ar.GetUpperBound(0); i++)
			{
				var rv = new string[ar.GetUpperBound(1)+1];
				for (var j = 0; j <= ar.GetUpperBound(1); j++)
				{
					rv[j] = ar[i, j];
				}
				yield return rv;
			}
		}
	}
}
